
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using JYJ.AiYard.StationManagement.TbYardStations;
using JYJ.AiYard.StationManagement.TbYardStations.Dtos;
using JYJ.AiYard.StationManagement.TbYardStations.DomainService;
using JYJ.AiYard.StationManagement.TbYardStations.Authorization;
using JYJ.AiYard.Database;
using Microsoft.AspNetCore.Http;
using JYJ.AiYard.StationManagement.YardCommonHald;
using JYJ.AiYard.StationManagement.YardReport;

namespace JYJ.AiYard.StationManagement.TbYardStations
{
    /// <summary>
    /// TbYardStation应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbYardStationAppService : AiYardAppServiceBase, ITbYardStationAppService
    {
        private readonly IRepository<TbYardStation, long> _entityRepository;

        private readonly ITbYardStationManager _entityManager;

        private readonly IRepository<JYJ.AiYard.StationManagement.TbObjects.TbObjects, long> _entityObjectRepository;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;
        private readonly IHttpService _httpService;

        protected IHttpContextAccessor _httpContext;
        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbYardStationAppService(
        IRepository<TbYardStation, long> entityRepository,
        IRepository<JYJ.AiYard.StationManagement.TbObjects.TbObjects, long> entityObjectRepository,
        ITbYardStationManager entityManager,
        IAiYardDbTableIssuedCard aiYardDbTableIssuedCard
        , IHttpService httpService
        , IHttpContextAccessor httpContextAccessor
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
            _entityObjectRepository = entityObjectRepository;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
            _httpService = httpService;
            _httpContext = httpContextAccessor;
        }


        /// <summary>
        /// 获取TbYardStation的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbYardStationPermissions.Query)] 
        public async Task<PagedResultDto<TbYardStationListDto>> GetPaged(GetTbYardStationsInput input)
		{
            List<long> StationList = new List<long>();
            tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
            if (filterText.StationId == null || filterText.StationId <= 0)
            {
                StationList = GetCurrenUserOrganizationAndChildrenUnit();
            }
            else
            {
                StationList.Add((long)filterText.StationId);
            }
            var query = _entityRepository.GetAll().Where(o => StationList.Contains(o.Station_ID));
            // TODO:根据传入的参数添加过滤条件
            if (!string.IsNullOrEmpty(filterText.FilterText))
            {
                query = query.Where(o => o.Yard_Name.Contains(filterText.FilterText));
            }

			var count = await query.CountAsync();

			var entityList = await query 
                    .OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();


             
			var entityListDtos =entityList.MapTo<List<TbYardStationListDto>>();
            await FillObjNameAsync(entityListDtos);
			return new PagedResultDto<TbYardStationListDto>(count,entityListDtos);
		}

        private async Task FillObjNameAsync(List<TbYardStationListDto> stationlistDto)
        {
            //List<TbYardStationListDto> st = new List<TbYardStationListDto>();
            if (stationlistDto.Count > 0)
            {
                for (int i = 0; i < stationlistDto.Count; i++)
                {
                    List<int> strObject = new List<int>();
                    string ParkCardTypeId = stationlistDto[i].ParkCardTypeId;
                    if (!string.IsNullOrEmpty(ParkCardTypeId))
                    {
                        for (int j = 0; j < ParkCardTypeId.Split(',').Length; j++)
                        {                          
                            try { strObject.Add(Convert.ToInt32(ParkCardTypeId.Split(',')[j])); } catch { }
                        }

                        var tbObject = _entityObjectRepository.GetAll().Where(o => o.Station_ID == stationlistDto[i].Station_ID && strObject.Contains(o.OBJ_ID)).ToList();

                        var allObject = tbObject.MapTo<List<JYJ.AiYard.StationManagement.TbObjects.Dtos.StationObjectsDTO>>();
                        stationlistDto[i].parkCardTypeIdObjects = allObject;
                    }

                    strObject.Clear();
                    string GuestCardTypeId = stationlistDto[i].GuestCardTypeId;
                    if (!string.IsNullOrEmpty(GuestCardTypeId))
                    {
                        for (int j = 0; j < GuestCardTypeId.Split(',').Length; j++)
                        {                         
                            try { strObject.Add(Convert.ToInt32(GuestCardTypeId.Split(',')[j])); } catch { }
                        }

                        var tbObject = _entityObjectRepository.GetAll().Where(o => o.Station_ID == stationlistDto[i].Station_ID && strObject.Contains(o.OBJ_ID)).ToList();

                        var allObject = tbObject.MapTo<List<JYJ.AiYard.StationManagement.TbObjects.Dtos.StationObjectsDTO>>();
                        stationlistDto[i].guestCardTypeIdObjects = allObject;
                    }
                    strObject.Clear();
                    string MonthCardTypeId = stationlistDto[i].MonthCardTypeId;
                    if (!string.IsNullOrEmpty(MonthCardTypeId))
                    {
                        for (int j = 0; j < MonthCardTypeId.Split(',').Length; j++)
                        {                           
                            try { strObject.Add(Convert.ToInt32(MonthCardTypeId.Split(',')[j])); } catch { }
                        }

                        var tbObject = _entityObjectRepository.GetAll().Where(o => o.Station_ID == stationlistDto[i].Station_ID && strObject.Contains(o.OBJ_ID)).ToList();

                        var allObject = tbObject.MapTo<List<JYJ.AiYard.StationManagement.TbObjects.Dtos.StationObjectsDTO>>();
                        stationlistDto[i].monthCardTypeIdObjects = allObject;
                    }
                }
            }

            //return st;
        }


        /// <summary>
        /// 通过指定id获取TbYardStationListDto信息
        /// </summary>
        [AbpAuthorize(TbYardStationPermissions.Query)] 
		public async Task<TbYardStationListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbYardStationListDto>();
		}

        public async Task<List<TbYardStationListDto>> GetAllTbYardStationLists(long StationId)
        {
            
            var tbStation = await _entityRepository.GetAll().Where(o => o.Station_ID == StationId).ToListAsync();

            var alltbStation = tbStation.MapTo<List<TbYardStationListDto>>();    

            return alltbStation;
        }

        /// <summary>
        /// 获取编辑 TbYardStation
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardStationPermissions.Create,TbYardStationPermissions.Edit)]
		public async Task<GetTbYardStationForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbYardStationForEditOutput();
                TbYardStationEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);
                long StationId = entity.Station_ID;

                editDto = entity.MapTo<TbYardStationEditDto>();

                List<int> strObject = new List<int>();
                string ParkCardTypeId = editDto.ParkCardTypeId;
                if (!string.IsNullOrEmpty(ParkCardTypeId))
                {
                    for (int j = 0; j < ParkCardTypeId.Split(',').Length; j++)
                    {
                        try { strObject.Add(Convert.ToInt32(ParkCardTypeId.Split(',')[j])); } catch { }
                    }

                    var tbObject = _entityObjectRepository.GetAll().Where(o => o.Station_ID == StationId && strObject.Contains(o.OBJ_ID)).ToList();

                    var allObject = tbObject.MapTo<List<JYJ.AiYard.StationManagement.TbObjects.Dtos.StationObjectsDTO>>();
                    output.parkCardTypeIdObjects = allObject;
                }

                strObject.Clear();
                string GuestCardTypeId = editDto.GuestCardTypeId;
                if (!string.IsNullOrEmpty(GuestCardTypeId))
                {
                    for (int j = 0; j < GuestCardTypeId.Split(',').Length; j++)
                    {                       
                        try { strObject.Add(Convert.ToInt32(GuestCardTypeId.Split(',')[j])); } catch { }
                    }

                    var tbObject = _entityObjectRepository.GetAll().Where(o => o.Station_ID == StationId && strObject.Contains(o.OBJ_ID)).ToList();

                    var allObject = tbObject.MapTo<List<JYJ.AiYard.StationManagement.TbObjects.Dtos.StationObjectsDTO>>();
                    output.guestCardTypeIdObjects = allObject;
                }
                strObject.Clear();
                string MonthCardTypeId = editDto.MonthCardTypeId;
                if (!string.IsNullOrEmpty(MonthCardTypeId))
                {
                    for (int j = 0; j < MonthCardTypeId.Split(',').Length; j++)
                    {                     
                        try { strObject.Add(Convert.ToInt32(MonthCardTypeId.Split(',')[j])); } catch { }
                    }

                    var tbObject = _entityObjectRepository.GetAll().Where(o => o.Station_ID == StationId && strObject.Contains(o.OBJ_ID)).ToList();

                    var allObject = tbObject.MapTo<List<JYJ.AiYard.StationManagement.TbObjects.Dtos.StationObjectsDTO>>();
                    output.monthCardTypeIdObjects = allObject;
                }
                 
            }
			else
			{
				editDto = new TbYardStationEditDto();
			}

            

			output.TbYardStation = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbYardStation的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardStationPermissions.Create,TbYardStationPermissions.Edit)]
		public async Task CreateOrUpdate(CreateOrUpdateTbYardStationInput input)
		{
            if (input.TbYardStation.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            }
            if (input.TbYardStation.Id.HasValue)
			{
				await Update(input.TbYardStation);
			}
			else
			{
				await Create(input.TbYardStation);
			}
		}


        /// <summary>
        /// 新增TbYardStation
        /// </summary>
        [AbpAuthorize(TbYardStationPermissions.Create)]
		protected virtual async Task<TbYardStationEditDto> Create(TbYardStationEditDto input)
		{
            //TODO:新增前的逻辑判断，是否允许新增
           
            var entity=input.MapTo<TbYardStation>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<TbYardStationEditDto>();
		}

		/// <summary>
		/// 编辑TbYardStation
		/// </summary>
		[AbpAuthorize(TbYardStationPermissions.Edit)]
		protected virtual async Task Update(TbYardStationEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);
             
		    await _entityRepository.UpdateAsync(entity);
		} 

        /// <summary>
        /// 删除TbYardStation信息的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbYardStationPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
        {
            if (_aiYardDbTableIssuedCard.CheckIsForeignKey(input.Id, 0, "YardStation"))
            {
                throw new Exception(input.Id + "存在外键约束，不允许删除");
            }
            //TODO:删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbYardStation的方法
		/// </summary>
		[AbpAuthorize(TbYardStationPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
            foreach (long Id in input)
            {
                if (_aiYardDbTableIssuedCard.CheckIsForeignKey(Id, 0, "YardStation"))
                {
                    throw new Exception(Id + "存在外键约束，不允许删除");
                }
            }
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		///// <summary>
		///// 导出TbYardStation为excel表,等待开发。
		///// </summary>
		///// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


